﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Diagnostics;

//DDI Survey Reader: Lucas Moffitt
//                   LucasMoffitt@Gmail.com
//                   @LucasMoffitt
namespace DDI_Survey_Reader
{
    public partial class frm_Main : Form
    {
        //Holds Namespace References, Integers, Strings and Arrays for the project.
        #region Declarations

        int SurveyQuestionCount, CitationItemCount;

        List<string> ArrayAnswerValues = new List<string>();
       
        //Reference DDI3 XML Namespaces
        XNamespace ddi = "ddi:instance:3_1";
        XNamespace p = "ddi:physicaldataproduct:3_1";
        XNamespace l = "ddi:logicalproduct:3_1";
        XNamespace d = "ddi:datacollection:3_1";
        XNamespace a = "ddi:archive:3_1";
        XNamespace c = "ddi:conceptualcomponent:3_1";
        XNamespace s = "ddi:studyunit:3_1";
        XNamespace r = "ddi:reusable:3_1";

        #endregion
        
        public frm_Main()
        {
            InitializeComponent();
        }

        //On Form load.
        private void frm_Main_Load(object sender, EventArgs e)
        {
            //Set to the Getting Started Tab and change alignment so it can't be seen.
            tab_Main.SelectedIndex = 0;
            tab_Main.Alignment = TabAlignment.Right;
        }

        //Load the XML Document.
        private void OpenSurvey()
        {
            //Show the Default Panel while we clean up
            tab_Main.SelectedIndex = 0;
            
            if (dlg_OpenFile.ShowDialog() == DialogResult.OK)
            {
                //Clear all the crap to make sure the form is empty before being filled
                Survey_Layout.Controls.Clear();
                Citation_Layout.Controls.Clear();

                Survey_Layout.RowStyles.Clear();
                Citation_Layout.RowStyles.Clear();

                //Reset Counters
                SurveyQuestionCount = 0;
                CitationItemCount = 0;

                //Load the Survey
                LoadSurvey(dlg_OpenFile.FileName);

                //Show the Citation Panel
                tab_Main.SelectedIndex = 1;
            }
        }
        
        //Load all items within a survey.
        private void LoadSurvey(string Filelocation)
        {

            try
            {

                //Load the XML Document.
                XDocument SurveyXMLDocument = XDocument.Load(Filelocation);
                //Find the Root Element.
                XElement RootElement = SurveyXMLDocument.Root;

                //Read XML Document, Extract Citation information, Load to Citation Layout.
                #region Load Citation Information

                //Citation Elements.
                foreach (XElement CitationElement in RootElement.Descendants(s + "StudyUnit").Descendants(r + "Citation").Descendants())
                {

                    Citation_Layout.Controls.Add(ControlFactory.CreateControl("Label", CitationItemCount, CitationElement.Name.ToString()), 0, CitationItemCount);
                    Citation_Layout.Controls.Add(ControlFactory.CreateControl("TextBox", CitationItemCount, CitationElement.Value), 1, CitationItemCount);

                    CitationItemCount++;
                }

                //Abstract Element.
                Citation_Layout.Controls.Add(ControlFactory.CreateControl("Label", CitationItemCount, "Abstract"), 0, CitationItemCount);
                Citation_Layout.Controls.Add(ControlFactory.CreateControl("LargeTextBox", CitationItemCount, RootElement.Element(s + "StudyUnit").Element(s + "Abstract").Element(r + "Content").Value), 1, CitationItemCount);

                CitationItemCount++;
            
                //Purpose Element.
                Citation_Layout.Controls.Add(ControlFactory.CreateControl("Label", CitationItemCount, "Purpose"), 0, CitationItemCount);
                Citation_Layout.Controls.Add(ControlFactory.CreateControl("LargeTextBox", CitationItemCount, RootElement.Element(s + "StudyUnit").Element(s + "Purpose").Element(r + "Content").Value), 1, CitationItemCount);

                CitationItemCount++;

                #endregion

                //Read XML Document, Extract all questions, Load to Layout Table.
                #region Load Questions

                //Load Questions (QuestionScheme > QuestionItem).
                #region QuestionScheme>QuestionItem

                var SurveyQuestions = RootElement.Descendants(d + "QuestionScheme").Elements(d + "QuestionItem");

                //foreach QuestionItem.
                foreach (var Question in SurveyQuestions)
                {

                    //Load Question Text.
                    Survey_Layout.Controls.Add(ControlFactory.CreateControl("Label", SurveyQuestionCount, (Question.Element(d + "QuestionText").Element(d + "LiteralText").Element(d + "Text").Value)), 0, SurveyQuestionCount);

                    try
                    {
                        //Find if there's a CodeSchemeID available for the current QuestionItem.
                        var CodeSchemeQuery = from CodeSchemeID in RootElement.Descendants(l + "LogicalProduct").Elements(l + "CodeScheme").Attributes("id")
                                              where CodeSchemeID.Value == Question.Element(d + "CodeDomain").Element(r + "CodeSchemeReference").Element(r + "ID").Value
                                              select CodeSchemeID;

                        //foreach CodeSchemeID found the QuestionItem
                        foreach (XAttribute CodeSchemeQueryResult in CodeSchemeQuery)
                        {

                            //Find if there is a CategorySchemeID that matches the CodeSchemeID.
                            var CategorySchemeQuery = from CategorySchemeID in RootElement.Descendants(l + "LogicalProduct").Elements(l + "CategoryScheme").Attributes("id")
                                                      where CategorySchemeID.Value == CodeSchemeQueryResult.Parent.Element(l + "CategorySchemeReference").Element(r + "ID").Value
                                                      select CategorySchemeID;

                            //foreach CategoryScheme that is linked to the CodeSchemeID (Should Only Return One).
                            foreach (XAttribute CategorySchemeQueryResult in CategorySchemeQuery)
                            {

                                //Find how many Items are in the CategoryScheme.
                                var AnswerItems = CategorySchemeQueryResult.Parent.Descendants(l + "Category").Elements(r + "Label");

                                //For each Item found.
                                foreach (var Answer in AnswerItems)
                                {

                                    //Add Values into array.
                                    ArrayAnswerValues.Add(Answer.Value);

                                }

                                Survey_Layout.Controls.Add(ControlFactory.CreateControl("ComboBox", SurveyQuestionCount, ArrayAnswerValues.ToArray()), 1, SurveyQuestionCount);

                                ArrayAnswerValues.Clear();
                                SurveyQuestionCount++;
                                                                                                
                            }
                        }

                    }

                    //If there's no CodeItem, (Doesn't link to an answer response).
                    catch (NullReferenceException)
                    {
                        //Add a blank textbox and increase question counter.
                        Survey_Layout.Controls.Add(ControlFactory.CreateControl("TextBox", SurveyQuestionCount, ""), 1, SurveyQuestionCount);
                        SurveyQuestionCount++;
                     }

                    //General Error Catching for each new QuestionItem.
                    catch (Exception QuestionItemException)
                    {
                        Debug.WriteLine("Finding Question Item Error: " + QuestionItemException.Message);
                    }
                    
                }

                #endregion

                //Load Questions (QuestionScheme > MultipleQuestionItem > QuestionItem)
                #region QuestionScheme>MultipleQuestionItem>QuestionItem

                var SurveyMultipleQuestion = RootElement.Descendants(d + "QuestionScheme").Elements(d + "MultipleQuestionItem");

                //foreach MultipleQuestionItem
                foreach (var Question in SurveyMultipleQuestion)
                {
                    //Load main Question Text
                    Survey_Layout.Controls.Add(ControlFactory.CreateControl("Label", SurveyQuestionCount, (Question.Element(d + "QuestionText").Element(d + "LiteralText").Element(d + "Text").Value)), 0, SurveyQuestionCount);

                    //Increase Question Count so that the answers start on the next line.
                    SurveyQuestionCount++;

                    //Define QuestionItems contained in MultiplQuestionItem.
                    var SurveyMultipleQuestionItems = Question.Elements(d + "SubQuestions").Elements(d + "QuestionItem");

                    //foreacher QuestionItem in MultipleQuestionItem.
                    foreach (var MultipleQuestionItem in SurveyMultipleQuestionItems)
                    {

                        try
                        {
                            
                            //Find how many Items are in the CategoryScheme.
                            var AnswerItems = SurveyMultipleQuestionItems.Elements(d + "QuestionText").Elements(d + "LiteralText").Elements(d + "Text");

                            //For each Item found.
                            foreach (var Answer in AnswerItems)
                            {

                                if (ArrayAnswerValues.Contains(Answer.Value))
                                {
                                    //This is where I can put logic to use the Variable Entries to determine how many should be available
                                }
                                else
                                {
                                    ArrayAnswerValues.Add(Answer.Value);

                                    Survey_Layout.Controls.Add(ControlFactory.CreateControl("CheckBox", SurveyQuestionCount, Answer.Value), 1, SurveyQuestionCount);
                                    SurveyQuestionCount++;
                                }

                            }
                                              
                        }

                        //Error Catching for each new QuestionItem in MultipleQuestionItem
                        catch (Exception MultipleQuestionItemException)
                        {
                            Debug.WriteLine("Finding Question Items in MultipleQuestionItem Error: " + MultipleQuestionItemException.Message);
                        }

                    }

                    //After the end of each MultipleQuestionItem increase the main question counter and clear the array.
                    ArrayAnswerValues.Clear();
                    SurveyQuestionCount++;
                }
                
                #endregion
                
                //End Region - Load Questions
                #endregion

            }

            //Error Catching for whole LoadSurvey
            catch (Exception LoadSurveyException)
            {
                Debug.WriteLine("Load Survey Error: " + LoadSurveyException.Message);
            }

        }
            
        //Handles Updating the print view information after the survey has been loaded.
        private void UpdatePrintView()
        {

            //Work in Progress
           
        }

        //Handles the actions for each menu item button.
        #region MenuItems

              //Open Survey Button
              private void btn_LoadFile_Click(object sender, EventArgs e)
              {
                  OpenSurvey();
                  btn_Citation.Enabled = true;
                  btn_Questions.Enabled = true;
                  

              }

              //Exit Button
              private void btn_Exit_Click(object sender, EventArgs e)
              {
                  Application.Exit();
              }

              //Open Webpage to Report bug on Codeplex
              private void btn_Bug_Click(object sender, EventArgs e)
              {
                  Process.Start("http://ddisurveyreader.codeplex.com/workitem/list/advanced");
              }

              //Open Webpage to read the current licence on Codeplex
              private void btn_Licence_Click(object sender, EventArgs e)
              {
                  Process.Start("http://ddisurveyreader.codeplex.com/license");
              }

              //Open Webpage to see project documentation
              private void btn_Documentation_Click(object sender, EventArgs e)
              {
                  Process.Start("http://ddisurveyreader.codeplex.com/documentation");
              }

              //Show the Citation Panel
              private void btn_Citation_Click(object sender, EventArgs e)
              {
                  tab_Main.SelectedIndex = 1;
              }
             
              //Show the Questions Panel
              private void btn_Questions_Click(object sender, EventArgs e)
              {
                  tab_Main.SelectedIndex = 2;
              }

              //Show the About Panel
              private void btn_About_Click(object sender, EventArgs e)
              {
                  tab_Main.SelectedIndex = 3;
              }

              //Show the Print Panel
              private void btn_Print_Click(object sender, EventArgs e)
              {
                  tab_Main.SelectedIndex = 4;
              }

              //Social Contact Buttons
              #region SocialButtons

              private void btn_Social_Facebook_Click(object sender, EventArgs e)
              {
                  Process.Start("http://www.facebook.com/LucasMoffitt");
              }

              private void btn_Social_Twitter_Click(object sender, EventArgs e)
              {
                  Process.Start("http://twitter.com/LucasMoffitt");
              }

              private void btn_Social_RSS_Click(object sender, EventArgs e)
              {
                  Process.Start("http://www.lucasmoffitt.com/?feed=rss2");
              }

              private void btn_Social_LinkedIN_Click(object sender, EventArgs e)
              {
                  Process.Start("http://www.linkedin.com/profile/view?id=84678384");
              }

              #endregion

                   
        #endregion

    }
}
